#include "ChatHttpServer.h"
/***
 * @Author: 玄绮 shijiahansi@qq.com
 * @Date: 2024-06-09 14:12:26
 * @LastEditors: 玄绮 shijiahansi@qq.com
 * @LastEditTime: 2024-06-09 14:12:26
 * @FilePath: \server\src\server\app\HttpServer.cpp
 * @Description:
 * @
 * @Copyright (c) 2024 by 玄绮, All Rights Reserved.
 */
#include <HttpServer.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/erase.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/asio.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/beast.hpp>
#include <boost/beast/core/error.hpp>
#include <boost/date_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/json/kind.hpp>
#include <boost/json/object.hpp>
#include <boost/json/serialize.hpp>
#include <filesystem>
#include <string>
#include <system/System.h>
using namespace boost::date_time;
using namespace boost::gregorian;
namespace fs = std::filesystem;

using namespace rdhttp;

ChatHttpServer::ChatHttpServer(boost::asio::io_context& ctx, std::int32_t port, std::string doc_root)
    : rdhttp::HttpServer(ctx, port, doc_root) {
    init();
}

void ChatHttpServer::init() {
    post("/uploadfile") = post_handler(&ChatHttpServer::uploadfile);
}

void ChatHttpServer::uploadfile(rdhttp::HttpRequest& request, rdhttp::HttpResponse& response) {
    auto content_type = ContentType(request[HttpFiled::content_type]);

    if (content_type == ContentType::multipart_form_data) {
        auto const& forms = request.forms();

        for (auto& i : forms) {
            auto filename = i.content_dispotion().filename();
            std::cout << "filename:" << filename << std::endl;
            fs::path path(doc_root);

            boost::gregorian::date dateToday = boost::gregorian::day_clock::local_day();
            auto today                       = boost::gregorian::to_iso_string(dateToday);

            path /= today;
            path /= filename;

            if (i.save_as(path)) {
                boost::json::value res;
                auto file_path = path.string();
                boost::replace_all(file_path, "\\", "/");
                file_path.erase(0, doc_root.size());
                std::string file_url = domain + ":" + std::to_string(port) + file_path;
                res                  = {{"status", {{"code", 0},
                                                       {"message", "成功"}}},
                                     {"url", file_url}};

                response.body() = boost::json::serialize(res);
            }
        }
    }
    response.result(HttpStatus::ok);
}
